<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <!-- <a-popconfirm
          title="是否确认设置为主材？"
          ok-text="是"
          cancel-text="否"
          placement="bottom"
          @confirm="handleMainMaterial()"
        >
          <a-button type="success" v-auth="'btn:set:zucai'">
            <Icon icon="ant-design:setting-outlined" /> {{ t('设置为主材') }}
          </a-button>
        </a-popconfirm>
        <a-popconfirm
          title="是否确认取消主材？"
          ok-text="是"
          cancel-text="否"
          placement="bottom"
          @confirm="handleCancelMain()"
        >
          <a-button type="danger" v-auth="'btn:zucai:cancel'">
            <Icon icon="ant-design:close-circle-outlined" /> {{ t('取消主材') }}
          </a-button>
        </a-popconfirm> -->
        <a-popconfirm
          title="是否确认刷新材料？"
          ok-text="是"
          cancel-text="否"
          placement="bottom"
          @confirm="handleRefresh()"
        >
          <a-button type="primary" v-auth="'btn:refresh:zucai'" :loading="loading">
            <Icon icon="ant-design:sync-outlined" /> {{ t('从U8刷新') }}
          </a-button>
        </a-popconfirm>
        <a-button type="success" @click="handleMaterial()" v-auth="'btn:fenpeishuliang'">
          <Icon icon="ant-design:setting-outlined" /> {{ t('材料分配') }}
        </a-button>
        <!-- <a-popconfirm
          title="是否确认分配？"
          ok-text="是"
          cancel-text="否"
          placement="bottom"
          @confirm="handleConfirm()"
        >
          <a-button type="success" v-auth="'btn:querenfenpei'">
            <Icon icon="ant-design:check-circle-outlined" /> {{ t('确认分配') }}
          </a-button>
        </a-popconfirm> -->
      </template>
      <template #firstColumn="{ record }">
        <!-- <a @click="handleForm({ id: record.id })">
          
        </a> -->
        {{ record.name }}
      </template>

      <template #projectno="{ record }">
        <!-- <a @click="handleDetailsForm(record)" >
          <span style="text-decoration: underline;margin-right: 5px;">查看</span>
        </a>
        {{ record.pcode }} -->
        <a @click="handleDetailsForm(record)">
          {{ record.pcode }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />

    <BasicModal @register="register1" :title="'分配变更'" @ok="handleSubmit1">
      <div style="margin-top: 50px; font-size: 20px; padding: 10px">
        <!-- <Icon
          icon="simple-line-icons:question"
          style="margin-right: 10px; color: #f39c12; font-size: 30px"
        /> -->
        <!-- 确认修改[已完成]状态？ -->
        选中记录存在<span style="color: red">已分配</span>材料，是否确认继续？
      </div>
    </BasicModal>

    <!-- 选项目 -->
    <BasicModal v-bind="$attrs" @register="registerModal" title="从U8刷新" @ok="handleModal">
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialBomPmMaterialList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    pmMaterialDelete,
    pmMaterialListData,
    pmMaterialSetMain,
    pmMaterialCancelMain,
    pmMateriallConfirm,
    pmMaterialRefresh,
  } from '/@/api/material/bom/pmMaterial';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './fpForm.vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  const { t } = useI18n('material.bom.pmMaterial');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: router.currentRoute.value.meta.title || t('材料清单管理'),
    value: t('材料分配'),
  };
  let loading = ref(false);
  const props = defineProps({
    projectno: { type: String, default: '' },
  });

  // 时间格式化日期，只保留年月日
  const formatDate = (date: string) => {
    if (!date) return '';
    const dateObj = new Date(date);
    const year = dateObj.getFullYear();
    const month = dateObj.getMonth() + 1;
    const day = dateObj.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      // {
      //   label: t('创建时间'),
      //   field: 'createtime',
      //   component: 'DatePicker',
      //   componentProps: {
      //     format: 'YYYY-MM-DD HH:mm',
      //     showTime: { format: 'HH:mm' },
      //   },
      // },
      {
        label: t('工程编码'),
        field: 'pcode',
        component: 'Input',
      },
      {
        label: t('工程名称'),
        field: 'name',
        component: 'Input',
      },
      // {
      //   label: t('工程名称'),
      //   field: 'name',
      //   component: 'Input',
      // },
      // {
      //   label: t('设计变更编码'),
      //   field: 'sno',
      //   component: 'Input',
      //   ifShow: false,
      // },
      // {
      //   label: t('分单编码'),
      //   field: 'fdno',
      //   component: 'Input',
      // },
      {
        label: t('物料编码'),
        field: 'mcode',
        component: 'Input',
      },
      {
        label: t('物料名称'),
        field: 'mname',
        component: 'Input',
      },
      {
        label: t('规格型号'),
        field: 'mstd',
        component: 'Input',
      },
      // {
      //   label: t('单位'),
      //   field: 'unit',
      //   component: 'Input',
      // },
      // {
      //   label: t('标识标识'),
      //   field: 'istart',
      //   component: 'Input',
      //   ifShow: false,
      // },
      // {
      //   label: t('是否主材'),
      //   field: 'bmain',
      //   component: 'Select',
      //   componentProps: {
      //     dictType: 'sys_yes_no',
      //   },
      // },
      {
        label: t('分配状态'),
        field: 'fpStatus_in',
        component: 'Select',
        componentProps: {
          dictType: 'zf_mat_fp_status',
          allowClear: true,
          mode: 'multiple',
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('工程编码'),
      dataIndex: 'pcode',
      key: 'a.pcode',
      sorter: true,
      width: 180,
      align: 'left',
      slot: 'projectno',
    },
    {
      title: t('工程名称'),
      dataIndex: 'name',
      key: 'a.name',
      sorter: true,
      width: 300,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('物料编码'),
      dataIndex: 'mcode',
      key: 'a.mcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('物料名称'),
      dataIndex: 'mname',
      key: 'a.mname',
      sorter: true,
      width: 300,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'mstd',
      key: 'a.mstd',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('数量'),
      dataIndex: 'num',
      key: 'a.num',
      sorter: true,
      width: 80,
      align: 'right',
    },
    {
      title: t('单位'),
      dataIndex: 'unit',
      key: 'a.unit',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('请购量'),
      dataIndex: 'puQty',
      key: 'a.pu_qty',
      sorter: true,
      width: 100,
      align: 'right',
    },
    {
      title: t('库领量'),
      dataIndex: 'stQty',
      key: 'a.st_qty',
      sorter: true,
      width: 100,
      align: 'right',
    },
    {
      title: t('累计请购'),
      dataIndex: 'sumPuQty',
      key: 'a.sum_pu_qty',
      sorter: true,
      width: 100,
      align: 'right',
    },
    {
      title: t('累计库领'),
      dataIndex: 'sumStQty',
      key: 'a.sum_st_qty',
      sorter: true,
      width: 100,
      align: 'right',
    },
    {
      title: t('现存量'),
      dataIndex: 'pmStock.iquantity',
      key: 'stock.iquantity',
      sorter: true,
      width: 80,
      align: 'right',
    },
    {
      title: t('最低库存'),
      dataIndex: 'pmStock.cInvDefine13',
      key: 'stock.cInvDefine13',
      sorter: true,
      width: 100,
      align: 'right',
    },
    // {
    //   title: t('分配人'),
    //   dataIndex: 'fpBy',
    //   key: 'a.fp_by',
    //   sorter: true,
    //   width: 100,
    //   align: 'left',
    // },
    {
      title: t('分配状态'),
      dataIndex: 'fpStatus',
      key: 'a.fp_status',
      sorter: true,
      width: 100,
      align: 'center',
      dictType: 'zf_mat_fp_status',
      fixed: 'right',
    },
    // {
    //   title: t('设计变更编码'),
    //   dataIndex: 'sno',
    //   key: 'a.sno',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
    // {
    //   title: t('分单编码'),
    //   dataIndex: 'fdno',
    //   key: 'a.fdno',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
    // {
    //   title: t('创建时间'),
    //   dataIndex: 'createtime',
    //   key: 'a.createtime',
    //   sorter: true,
    //   width: 100,
    //   align: 'left',
    //   ifShow: false,
    // },
    // {
    //   title: t('是否主材'),
    //   dataIndex: 'bmain',
    //   key: 'a.bmain',
    //   sorter: true,
    //   width: 100,
    //   align: 'center',
    //   dictType: 'sys_yes_no',
    //   fixed: 'right',
    // },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑材料分配'),
        onClick: handleForm.bind(this, record),
        auth: 'btn:bom:pmMaterial:update',
        ifShow: () => record.fpStatus === '2', // 已分配
      },
    ],
  };

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t('项目'),
        field: 'projectno',
        fieldLabel: 'projectname',
        component: 'TreeSelect',
        componentProps: {
          api: pmProjectinformationTreeData,
          params: {},
          allowClear: false,
          canSelectParent: false,
          immediate: true,
        },
        required: true,
        colProps: { lg: 24, md: 24 },
        itemProps: { validateTrigger: 'blur' },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();

  const [register1, { openModal: openModal1, closeModal: closeModal1 }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, getSelectRows, getSelectRowKeys }] = useTable({
    api: pmMaterialListData,
    beforeFetch: (params) => {
      params.ope = '2';
      return params;
    },
    columns: tableColumns,
    // actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    immediate: false,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleDetailsForm(record: Recordable) {
    router.push({
      path: '/proj/info/pmProjectinformation/detailsForm',
      query: {
        id: record.projInfo.id,
        code: record.pcode,
        tabTitle: `项目详情(${record.pcode})`,
      },
    });
  }

  function handleForm(record: Recordable) {
    //openDrawer(true, record);
    openDrawer(true, {
      list: [record],
    });
  }

  async function handleDelete(record: Recordable) {
    const res = await pmMaterialDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 刷新材料
  async function handleRefresh() {
    if (getSelectRows().length) {
      try {
        loading.value = true;
        let selIds = ref('');
        let arr = getSelectRows().map((item) => {
          return item.pcode;
        });
        let newArr = Array.from(new Set(arr));
        const res = await pmMaterialRefresh({ selIds: newArr.join(',') });
        showMessage(res.message);
        handleSuccess();

      } catch (error: any) {
        if (error && error.errorFields) {
            showMessage(t('刷新失败'));
        }
        console.log('error', error);
      } finally {
        loading.value = false;
      }

    } else {
      // showMessage('请先选择一条记录！');
      await openModal(true, {});
      resetFields();
    }
  }

  async function handleModal() {
    try {
      let data = await validate();
      setModalProps({ confirmLoading: true });
      const res = await pmMaterialRefresh({ selIds: data.projectno });
      showMessage(res.message);
      closeModal();
      handleSuccess();
      setModalProps({ confirmLoading: false });
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('刷新失败'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 设置为主材
  async function handleMainMaterial() {
    if (getSelectRows().length) {
      let selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await pmMaterialSetMain({ selIds: selIds.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择一条记录！');
    }
  }

  // 取消设置主材
  async function handleCancelMain() {
    if (getSelectRows().length) {
      let selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await pmMaterialCancelMain({ selIds: selIds.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择一条记录！');
    }
  }

  watch(
    () => props.projectno,
    () => {
      handleProjecte();
    },
  );

  onMounted(async () => {
    handleProjecte();
  });

  async function handleProjecte() {
    await getForm().setFieldsValue({
      pcode: props.projectno ? props.projectno : userStore.getProjecte.code,
      fpStatus_in: '0,1',
    });
    reload();
    await getForm().setFieldsValue({
      pcode: props.projectno ? props.projectno : userStore.getProjecte.code,
      fpStatus_in: '0,1',
    });
  }

  // 分配数量
  async function handleMaterial() {
    // if (getSelectRowKeys().length) {
    //   openDrawer(true, {
    //     list: getSelectRows(),
    //   });
    // } else {
    //   showMessage('请先选择一条记录！');
    // }

    if (getSelectRowKeys().length) {
      let flag = true;
      getSelectRows().forEach((item) => {
        if (item.fpStatus == '2') {
          flag = false;
        }
      });
      if (flag) {
        openDrawer(true, {
          list: getSelectRows(),
        });
      } else {
        openModal1(true);
      }
    } else {
      showMessage('请先选择一条记录！');
    }
  }

  async function handleSubmit1() {
    let list = getSelectRows().filter((item) => {
      return item.fpStatus != '2';
    });
    openDrawer(true, {
      list,
    });
    setTimeout(closeModal1);
  }

  // 分配确认
  async function handleConfirm() {
    if (getSelectRowKeys().length) {
      const res = await pmMateriallConfirm({ selIds: getSelectRowKeys().join(',') });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请先选择一条记录！');
    }
  }

  function handleSuccess() {
    reload();
  }
</script>
